package mybatisTest.jdbc;

import org.junit.Test;

import java.sql.*;

public class Conn {

    @Test
    public  void  test() throws SQLException {
        Connection conn = getConn();
        PreparedStatement pst = conn.prepareStatement("insert into user (name,age,sex) values (?,?,?)",Statement.RETURN_GENERATED_KEYS);
        pst.setString(1,"jdbc");
        pst.setInt(2,34);
        pst.setInt(3,98);
//        pst.execute();
        ResultSet keys = pst.getGeneratedKeys();
        if(keys.next()) {
            int anInt = keys.getInt(1);
            System.out.println(anInt);
        }
    }



    public static Connection getConn() {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/test";
        String username = "root";
        String password = "root";
        Connection conn = null;
        try {
            Class.forName(driver); //classLoader,加载对应驱动
            //DriverManager已经有了driver的信息
            conn = (Connection) DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}
